<?php
namespace app\admin\controller;


use app\admin\lib\AdminController;
use app\admin\model\ApiResponse;
use app\common\model\UserNoticeMessage;
use library\JPushZDY;
use think\Request;

class Message extends AdminController
{
    public function index(Request $request) {
        if ($request->isGet()) {
            return $this->list($request);
        } elseif ($request->isPost()) {
            return $this->save($request);
        } elseif ($request->isDelete()) {
            return $this->del($request);
        } else {
            return json([],404);
        }
    }

    protected function list(Request $request) {
        $model = new UserNoticeMessage();

        $type = $request->param('type');
        if ($type) $model->where('type', $type);
        $message_type = $request->param('message_type');
        if ($message_type) $model->where('message_type', $message_type);

        $model->order('id','desc');
        $result = $model->paginate($this->rows,false,['page' => $this->page]);
        foreach ($result->getCollection() as $item) {
            $item->decodeJson();
        }
        $re = $result->toArray();
        $re['code'] = 200;
        return $re;
    }

    protected function save(Request $request) {
        $data = $request->param();
        $model = new UserNoticeMessage();
        if(isset($data['id']) && $data['id']>0){
            $model->save($data,['id'=>$data['id']]);
        }else{
            $model->data($data);
            $model->save();
        }

        if (UserNoticeMessage::TYPE_PUBLIC == $model->type) {
            JPushZDY::pushAll($model->content,$model->extras);
        }

        /*$pushChannel = $request->param('push_channel');
        if (empty($pushChannel)) $pushChannel = [];
        elseif (!is_array($pushChannel)) $pushChannel = [$pushChannel];
        foreach ($pushChannel as $c) {
            if (UserNoticeMessage::TYPE_PRIVATE == $model->type) {
                if (1 == $c) JPushZDY::pushUsers($model->userid,$model->content,$model->extras);
            } elseif (UserNoticeMessage::TYPE_PUBLIC == $model->type) {
                JPushZDY::pushAll($model->content,$model->extras);
            }
        }*/

        return ApiResponse::success();
    }

    protected function del(Request $request) {
        $id = $request->param('id');
        UserNoticeMessage::destroy($id);
        return ApiResponse::success();
    }

}